package cn.edagr.utils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.util.Properties;

/**
 * 获取连接池对象
 */
public enum RedisUtils {
    //使用枚举实现单例
    INSTANCE;
	//连接池对象
    private static JedisPool jedisPool = null;

    static {
        //初始化链接池
        //1 创建连接池配置对象
        JedisPoolConfig config = new JedisPoolConfig();
        //2 进行配置-四个配置
        ////最小连接数
        config.setMaxIdle(1);
		//最大连接数
        config.setMaxTotal(11);
		//链接最长等待时间
        config.setMaxWaitMillis(10 * 1000L);
		//测试连接时是否畅通
        config.setTestOnBorrow(true);
       
        String host = "127.0.0.1";
        int port = 6379;
        String password = "123456";
        int timeout = 10000;

		//创建连接池
        jedisPool = new JedisPool(config, host,port,timeout, password);
    }

    //获取连接
    public Jedis getSource() {
        return jedisPool.getResource();
    }

    //关闭资源
    public void closeSource(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }

    }

    /* 
    * @Title: set
    * @Description: TODO
    * @Author: My.Yang
    * @Version: 1.0
    * @Date:  2022/6/28 15:57
    * @Parameters: 
    * @Return 
    */
    public void set(String key, String value) {
        Jedis jedis = getSource();
        jedis.set(key, value);
        closeSource(jedis);
    }
   /* 
   * @Title: setex
   * @Description: TODO
   * @Author: My.Yang
   * @Version: 1.0
   * @Date:  2022/6/28 15:56  
   * @Parameters: 
   * @Return 
   */
    public void setex(String key,int seconds, String value) {
        Jedis jedis = getSource();
        jedis.setex(key,seconds, value);
        closeSource(jedis);
    }

   /* 
   * @Title: get
   * @Description: TODO
   * @Author: My.Yang
   * @Version: 1.0
   * @Date:  2022/6/28 15:56  
   * @Parameters: 
   * @Return 
   */
    public String get(String key) {
        Jedis jedis = getSource();
        try {
            return jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeSource(jedis);
        }

        return null;

    }

    /* 
    * @Title: set
    * @Description: TODO
    * @Author: My.Yang
    * @Version: 1.0
    * @Date:  2022/6/28 15:56  
    * @Parameters: 
    * @Return 
    */
    public void set(byte[] key, byte[] value) {
        Jedis jedis = getSource();
        jedis.set(key, value);
        closeSource(jedis);
    }

  /* 
  * @Title: get
  * @Description: TODO
  * @Author: My.Yang
  * @Version: 1.0
  * @Date:  2022/6/28 15:56  
  * @Parameters: 
  * @Return 
  */
    public byte[]  get(byte[] key) {
        Jedis jedis = getSource();
        try {
            return jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeSource(jedis);
        }
        return null;

    }

}